package model.quadtree;
import java.awt.Rectangle;
import java.util.List;

import control.Config;


public class QuadTree {
	private Node root;
	//private boolean debug = false;
	private boolean stopVerifying;
	protected static final int minSize = 3;

	public QuadTree(Node root) {
		this.root = root;
		this.stopVerifying = false;
	}

	public void classifyNodes(List<Rectangle> obstacles)  
	{  
		preOrder(this.root, obstacles);
	}

	public void verifyGreys(List<Rectangle> obstacles){
		while(!stopVerifying){
			stopVerifying = true;
			classifyNodes(obstacles);
		}
	}

	protected void preOrder(Node node, List<Rectangle> obstacles)  
	{  
		if(node == null)  
			return; 
		node.classifyNode(obstacles); 
		debug(node);
		if(node.getChild()!=null){
			preOrder(node.getChild()[0], obstacles);
			preOrder(node.getChild()[1], obstacles);
			preOrder(node.getChild()[2], obstacles);
			preOrder(node.getChild()[3], obstacles);
		} 
		else{
			if(node.getType()==Type.GREY){
				if(node.getVert1().x - node.getVert2().x > minSize){
					makeChildren(node);
				}
			}
		}
	}

	public void makeChildren(Node node){
		node.makeChildren();
		stopVerifying = false;
	}

	protected void debug(Node child){
		if(Config.debugQuadTree){
			System.out.println("Node " + child.getId() + ":");
			if(child.getParent()!=null)
				System.out.println("   " + "Parent: "+child.getParent().getId());
			else
				System.out.println("   " + "is the ROOT");
			System.out.println("   " + "Type: "+child.getType());
			System.out.println("   " + "Vert1: "+child.getVert1());
			System.out.println("   " + "Vert2: "+child.getVert2());
			System.out.println();
		}
	}

	public Node getRoot() {
		return root;
	}

	public void setRoot(Node root) {
		this.root = root;
	}

	public boolean debug(){
		return Config.debugQuadTree;
	}
}
